#include "Task.hpp"
#include "RingQueue.hpp"
#include<ctime>
#include<cstdlib>
#include<pthread.h>
#include<unistd.h>
void* Consumer(void* _rq)
{
    //RingQueue<int>* rq = reinterpret_cast<RingQueue<int>*>(_rq)
    RingQueue<Task>* rq = reinterpret_cast<RingQueue<Task>*>(_rq);

    while(true)  //消费
    {
        Task t;
        rq->Pop(&t); 
        printf("消费者线程%0X :处理任务",pthread_self());
        t();

    }
    return nullptr;
}
void* Producter(void* _rq)
{
    //RingQueue<int>* rq = reinterpret_cast<RingQueue<int>*>(_rq);
    RingQueue<Task>* rq = reinterpret_cast<RingQueue<Task>*>(_rq);
    while(true)   // 生产
    {
        int x = rand()%10+1;
        int y = rand()%20+1;
        char op = "+-*/%"[rand()%5];
        Task t1(x,y,op);
        rq->Push(t1);
        printf("生产者线程%0X :生产了任务%d%c%d=?\n",pthread_self(),x,op,y);
    sleep(1);

    }
    return nullptr;
}


int main()
{
    srand((unsigned int)time(nullptr) ^ pthread_self());     //生产随机数种子
    //RingQueue<int>* rq = new RingQueue<int>();
    RingQueue<Task>* rq = new RingQueue<Task>();
    pthread_t Cpid[4];
    pthread_t Ppid[4];
    
    for(int i=0;i<4;++i)
    {
        pthread_create(&Cpid[i],nullptr,Consumer,rq);
    }
    for(int i=0;i<4;++i)
    {
        pthread_create(&Ppid[i],nullptr,Producter,rq);
    }


    for(int i=0;i<4;++i)
    {
        pthread_join(Cpid[i],nullptr);
        pthread_join(Ppid[i],nullptr);
    }
    return 0;
}
